package com.atguigu.edu.realtime.util;

import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Lec
 * @date 2022/8/15 21:26
 */

public class PhoenixUtil {

    public static void executeSql(String sql, Connection connection) {
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.execute();
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("Phoenix 建表语句或插入语句执行异常");
        } finally {
            close(preparedStatement, connection);
        }


    }

    private static void close(PreparedStatement preparedStatement, Connection connection) {
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {

            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    // select * from t where k=v and k1=v1
    // 设计方法考虑多行数据的返回
    public static <T> List<T> sqlQuery(Connection conn, String sql, Class<T> clz) {
        ArrayList<T> arrayList = new ArrayList<>();

        //如何给泛型的对象添加对应的属性
        PreparedStatement ps = null;
        try {
            ps = conn.prepareStatement(sql);
            ResultSet resultSet = ps.executeQuery();
/*/////////////////////////////////////////////////////////////////////*/
            //获取一行数据
            while (resultSet.next()) {
                //获取对应的元数据   即列名
                T t = clz.newInstance();
                ResultSetMetaData metaData = resultSet.getMetaData();
                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                    String columnName = metaData.getColumnName(i);
                    String value = resultSet.getString(i);
                    // 把_分割的大写的列名转换为小驼峰的属性名称
                    /*////////////////////////////*/
                    String propertyName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName);
                    BeanUtils.setProperty(t, propertyName, value);

                }
                arrayList.add(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("读取维度表数据错误");
        } finally {
            close(ps, conn);
        }
        return arrayList;
    }

}
